<template>
  <div class="app-container">
    <el-form ref="ruleForm" :model="rulesForm" :rules="formRules" label-width="100px">
      <el-row class="form_table" :gutter="10">
        <el-col :span="8">
          <el-form-item :label="$t('systemRules.ruleCode')" prop="ruleCode">
            <!-- :disabled="rulesForm.ruleCode" -->
            <el-input v-model.trim="rulesForm.ruleCode" clearable :disabled="!!$route.query.id" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item :label="$t('systemRules.ruleName')" prop="ruleName">
            <el-input v-model.trim="rulesForm.ruleName" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item :label="$t('systemRules.enabled')" prop="enabled">
            <el-select v-model="rulesForm.enabled" :placeholder="$t('placeholder.select')" clearable>
              <el-option v-for="item in $enableDict" :key="item.id" :label="item.text" :value="item.id" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item :label="$t('systemRules.routeManagement')" class="routeManagement">
        <!-- 请求路径参数 -->
        <el-card shadow="hover" class="ms_card">
          <div slot="header">
            <i class="el-icon-circle-plus-outline ms_icon" @click="addParam" />
          </div>

          <el-row v-for="(param, index) in rulesForm.queryParams" :key="index" :gutter="10">
            <el-col :span="5">
              <el-form-item :label="$t('systemRules.paramName') + ':'" :prop="'queryParams.' + index + '.name'" :rules="{ validator: checkPureNumber, trigger: 'blur' }">
                <el-input v-model.trim="param.name" />
              </el-form-item>
            </el-col>

            <el-col :span="5">
              <el-form-item :label="$t('systemRules.paramType') + ':'">
                <el-select v-model="param.type" clearable>
                  <el-option v-for="(item, i) in typeArray" :key="i" :label="item.text" :value="item.id" />
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="5">
              <el-form-item :label="$t('systemRules.paramDesc') + ':'">
                <el-input v-model.trim="param.desc" />
              </el-form-item>
            </el-col>

            <el-col :offset="2" :span="2">
              <el-checkbox v-model="param.require" :label="$t('systemRules.required')" border />
            </el-col>

            <el-col :span="2">
              <el-form-item label-width="10px">
                <i class="el-icon-close ms_list_icon" @click.prevent="removeParam(param)" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>
      </el-form-item>
      <!-- <el-row>
        <el-col :span="24" /> -->
      <!-- v-if="dialogTittle == 'edit'" -->
      <!-- <el-col :span="24" /> -->
      <!-- </el-row> -->
      <el-form-item :label="$t('systemRules.ruleContent')" prop="ruleContent">
        <el-input v-model.trim="rulesForm.ruleContent" type="textarea" :autosize="{ minRows: 5, maxRows: 12 }" clearable />
      </el-form-item>
      <el-form-item :label="$t('systemRules.testJson')" class="routeManagement">
        <vue-json-editor v-model="rulesForm.ruleDemo" :modes="['code']" :mode="'code'" :show-btns="false" lang="zh" :expanded-on-start="true" />
      </el-form-item>
      <el-form-item :label="$t('systemRules.executeResult')">
        <el-input v-model.trim="executeResult" type="textarea" :autosize="{ minRows: 3, maxRows: 6 }" :disabled="true" clearable />
      </el-form-item>
    </el-form>
    <div slot="footer" style="text-align: center">
      <el-button type="primary" plain @click="confirm">{{ $t('btn.confirm') }}</el-button>
      <el-button type="danger" plain @click="$router.back()">{{ $t('btn.close') }}</el-button>
      <!-- v-if="dialogTittle != 'add' && dialogTittle != 'view'" -->
      <el-button type="warning" plain @click="execute">{{ $t('btn.execute') }} </el-button>
    </div>
  </div>
</template>
<script>
import { deleteRules, rulesExecute, rulesPageList, rulesSave, rulesUpdate, rulesDetail } from '@/api/system-set'
import vueJsonEditor from 'vue-json-editor'
import { dataDictionary } from '@/api/common'

export default {
  name: 'RulesDetail',
  components: {
    vueJsonEditor,
  },
  data() {
    const checkPureNumber = (rule, value, callback) => {
      if (new RegExp(/^[0-9]+.?[0-9]*$/).test(value)) {
        callback(new Error('不能为纯数字'))
      } else {
        callback()
      }
    }
    return {
      checkPureNumber,
      id: '',
      executeResult: '',
      treeDialog: false,
      selectedList: [],
      searchForm: {
        ruleCode: null,
        ruleName: null,
        enabled: null,
        pageNumber: 1,
        pageSize: 10,
      },
      tableList: [],
      typeArray: [],
      total: 0,
      // dialogTittle: 'view',
      basicDialog: false,
      rulesForm: {
        ruleCode: null,
        ruleName: null,
        ruleContent: null,
        ruleFields: null,
        ruleDemo: {},
        enabled: 1,
        queryParams: [],
      },
      formRules: {
        ruleCode: [{ required: true, message: this.$t('placeholder.input'), trigger: 'blur' }],
        ruleName: [{ required: true, message: this.$t('placeholder.input'), trigger: 'blur' }],
        ruleContent: [{ required: true, message: this.$t('placeholder.input'), trigger: 'blur' }],
      },
    }
  },
  created() {
    this.init()
  },
  activated() {
    this.init()
  },
  deactivated() {
    this.$refs.ruleForm.resetFields()
  },
  methods: {
    init() {
      this.getDictionary()
      if (!this.rulesForm.ruleCode) {
        const id = this.$route.query.id
        if (id) {
          const accessKey = this.$route.query.accessKey
          this.getData(id, accessKey)
        }
      }
    },
    addParam() {
      this.rulesForm.queryParams.push({
        name: '',
        type: 'String',
        require: false,
        desc: '',
      })
    },
    // 提交按钮
    confirm() {
      this.$refs.ruleForm.validate(async(valid, obj) => {
        if (valid) {
          const formData = Object.assign({}, this.rulesForm)
          formData.ruleDemo = JSON.stringify(formData.ruleDemo)
          formData.ruleFields = JSON.stringify(this.rulesForm.queryParams)
          if (!this.$route.query.id) {
            const { code } = await rulesSave(formData)
            if (code != '200') return
            this.$router.back()
          } else {
            const { code } = await rulesUpdate(formData)
            if (code != '200') return
            this.$router.back()
          }
        } else {
          return
        }
      })
    },
    async execute() {
      const executeData = Object.assign({}, this.rulesForm)
      executeData.ruleDemo = JSON.stringify(this.rulesForm.ruleDemo)
      executeData.ruleFields = JSON.stringify(this.rulesForm.queryParams)
      const { code, data } = await rulesExecute(executeData)
      console.log(code)
      if (code == '200') {
        this.executeResult = data
      }
      //  else {
      //   const message = typeof data === 'object' ? JSON.stringify(data) : data
      //   this.$message.error(message)
      // }
    },

    // 查询
    async getData(id, accessKey) {
      const { code, data } = await rulesDetail(id, accessKey)
      if (code != '200') return
      // this.rulesForm = data
      this.rulesForm = {
        ...data,
        ruleDemo: JSON.parse(data.ruleDemo),
        queryParams: JSON.parse(data.ruleFields),
      }
      // this.rulesForm.ruleDemo = JSON.parse(this.rulesForm.ruleDemo)
      // this.rulesForm.queryParams = JSON.parse(this.rulesForm.ruleFields)
    },

    async getDictionary() {
      const res = await dataDictionary('RULE_PARAM_TYPE')
      if (res.code != '200') return
      this.typeArray = res.data
    },
    removeParam(item) {
      const index = this.rulesForm.queryParams.indexOf(item)
      if (index !== -1) {
        this.rulesForm.queryParams.splice(index, 1)
      }
    },
  },
}
</script>

<style>
.jsoneditor-poweredBy {
  display: none;
}
</style>
